package data.obj;

import java.util.Arrays;

public class Sheet
{
	double[][] table;
	double[] cols;
	double[] rows;

	public Sheet(double[][] table, double[] cols, double[] rows) throws Exception
	{
		super();
		this.table = table;
		this.cols = cols;
		this.rows = rows;
		checkConsistency();
	}

	public Sheet(double[][] rowTable) throws Exception
	{

		cols = new double[rowTable[0].length - 1];
		rows = new double[rowTable.length - 1];

		cols = Arrays.copyOfRange(rowTable[0], 1, rowTable[0].length);

		table = new double[rowTable.length - 1][rowTable[0].length - 1];
		for (int r = 0; r < rowTable.length - 1; r++)
		{
			if (r != 0)
				rows[r-1] = rowTable[r][0];
			for (int c = 0; c < rowTable[0].length - 1; c++)
			{
				table[r][c] = rowTable[r + 1][c + 1];
			}
		}
		checkConsistency();
	}

	private void checkConsistency() throws Exception
	{
		if (cols.length != table[0].length)
			throw new Exception("Sheet not Consistent: cols size not equal to table size");

		if (rows.length != table.length)
			throw new Exception("Sheet not Consistent: rows size not equal to table size");

	}

	public double getValue(double r, double c)
	{
		int realRow = 0;
		int realCol = 0;
		//c=24;
		//r=78;
		//r=12;

		for (int rIndex = 0; rIndex < rows.length-1; rIndex++)
		{
			if (r > rows[rIndex] && r <= rows[rIndex+1] )
				realRow = rIndex+1;

		}

		for (int cIndex = 0; cIndex < cols.length-1; cIndex++)
		{
			if (c > cols[cIndex] && c <= cols[cIndex+1])
				realCol = cIndex+1;

		}

		return table[realRow][realCol];

	}

}
